<?php
	date_default_timezone_set('America/Argentina/Buenos_Aires');

	ini_set('max_execution_time', 604800);

	define("APP_ID", "519942634775590");
	define("SECRET", "5ea51129a4ca16efdaa478bbddeb1465");
	define("APP_CANVAS", "http://www.pageposter.solo-dilo.com/");

	define("RANDOM", true);
	define("NO_WEIGHT_POST", 25);	// Post a url with no weight
	define("MAX_EXECUTION_TIME", 100);
	define("CURRENT_URL", "http://www.pageposter.solo-dilo.com/poster.php");

 	include_once('./dbcon.php');

	// Facebook PHP SDK v4.0.11

	// include required files form Facebook SDK

	require_once( '../Facebook/HttpClients/FacebookHttpable.php' );
	require_once( '../Facebook/HttpClients/FacebookCurl.php' );
	require_once( '../Facebook/HttpClients/FacebookCurlHttpClient.php' );

	require_once( '../Facebook/Entities/AccessToken.php' );
	require_once( '../Facebook/Entities/SignedRequest.php' );

	require_once( '../Facebook/FacebookSession.php' );
	require_once( '../Facebook/FacebookRedirectLoginHelper.php' );
	require_once( '../Facebook/FacebookRequest.php' );
	require_once( '../Facebook/FacebookResponse.php' );
	require_once( '../Facebook/FacebookSDKException.php' );
	require_once( '../Facebook/FacebookRequestException.php' );
	require_once( '../Facebook/FacebookOtherException.php' );
	require_once( '../Facebook/FacebookAuthorizationException.php' );
	require_once( '../Facebook/GraphObject.php' );
	require_once( '../Facebook/GraphSessionInfo.php' );
	require_once( '../Facebook/FacebookPermissionException.php' );

	use Facebook\HttpClients\FacebookHttpable;
	use Facebook\HttpClients\FacebookCurl;
	use Facebook\HttpClients\FacebookCurlHttpClient;

	use Facebook\Entities\AccessToken;
	use Facebook\Entities\SignedRequest;

	use Facebook\FacebookSession;
	use Facebook\FacebookRedirectLoginHelper;
	use Facebook\FacebookRequest;
	use Facebook\FacebookResponse;
	use Facebook\FacebookSDKException;
	use Facebook\FacebookRequestException;
	use Facebook\FacebookOtherException;
	use Facebook\FacebookAuthorizationException;
	use Facebook\GraphObject;
	use Facebook\GraphSessionInfo;
	use Facebook\FacebookPermissionException;

	error_reporting(E_ALL);

	$user_token = null;

	// IE compatible
	header('P3P: CP="NOI ADM DEV PSAi NAV OUR STP IND DEM"');

	// start session
	session_start();

	// init app with app id and secret
	FacebookSession::setDefaultApplication( APP_ID, SECRET );

	// login helper with redirect_uri
	$helper = new FacebookRedirectLoginHelper( APP_CANVAS );


	function post() {
		global $mysqli;

		$start_time = microtime(true);

		$page_id_condition = (isset($_GET['continue_from_page_id'])) ? "AND p.page_id > \"".$_GET['continue_from_page_id']."\"" : "";

		$pages_to_post = $mysqli->query("SELECT g.id as group_id, g.hours_of_day, g.sunday, g.monday, g.tuesday, g.wednesday, g.thursday, g.friday, g.saturday, p.page_id, a.value as access_token, g.from_page FROM groups g, pages p, access_tokens a WHERE g.id = p.group AND a.fb_id = g.from_page AND (p.blocked_for_posting = 0 OR p.blocked_for_posting IS NULL) ".$page_id_condition." ORDER BY p.page_id ASC");

		$hourOfDay = idate("H");

		while ($row = $pages_to_post->fetch_assoc()) {

			if (validDay($row) == false)
				continue;

			$validHours = explode(',', $row['hours_of_day']);
			if (!in_array($hourOfDay, $validHours))
				continue;

			$urlToPublish = getUrlToPublish($row['from_page']);

			$enganche = ($urlToPublish['enganche'] == null) ? getGlobalParameter('default_enganche') : $urlToPublish['enganche'];

			$template = $mysqli->query("SELECT template FROM templates WHERE group_id=".$row['group_id']." ORDER BY RAND() LIMIT 1");
			$template = $template->fetch_assoc();

			$message = $template['template'];
			$message = str_replace("[title]", $urlToPublish['title'], $message);
			$message = str_replace("[enganche]", $enganche, $message);
			$message = str_replace("[url]", $urlToPublish['url'], $message);

			$message = str_replace('\n', "\n", $message);

			try {

				$session = new FacebookSession( $row['access_token'] );

				$response = (new FacebookRequest(
						$session, 'POST', '/'.$row['page_id'].'/feed', array(
					'message' => $message,
					'link' => $urlToPublish['url'],
					'access_token' => $row['access_token']
					)
				))->execute()->getGraphObject();

				$mysqli->query("INSERT INTO posts (post_id, url_id, page_id, creation_date) VALUES ( '".$response->getProperty('id')."', ".$urlToPublish['id'].", '".$row['page_id']."', '".date('Y-m-d H:i:s')."')");

				if (microtime(true) - $start_time > MAX_EXECUTION_TIME) {
					echo CURRENT_URL."?continue_from_page_id=".$row['page_id'];
					exit();
				}

			} catch(FacebookRequestException $e) {
				$desc = $e->getCode().".".$e->getMessage().". For page_id=".$row['page_id'];
				$mysqli->query("INSERT INTO log (description, creation_date) VALUES ( '".$desc."', '".date('Y-m-d H:i:s')."')");
			}

		}
	}

	function getUrlToPublish($from_page) {
		global $mysqli;

		if (RANDOM) {
			$contents = $mysqli->query("SELECT * FROM urls WHERE from_page = '".$from_page."' ORDER BY RAND() LIMIT 1");
		
			return $contents->fetch_assoc();
		} else {

			if (rand(0,100) < NO_WEIGHT_POST) {
				$contents = $mysqli->query("SELECT * FROM urls WHERE from_page = '".$from_page."' AND (weight IS NULL OR weight = 0) ORDER BY RAND() LIMIT 1");

				if ($contents->num_rows > 0)
					return $contents->fetch_assoc();
			} 

			$contents = $mysqli->query("SELECT *, weight / (SELECT SUM(weight) FROM urls) as prob FROM urls WHERE weight IS NOT NULL AND from_page = '".$from_page."' ORDER BY prob DESC");
			$rand = rand(0, 10000);
			$last_value = 0;
			$last_row = null;

			while ($row = $contents->fetch_assoc()) {
				$last_row = $row;
				$last_value = $last_value + $row['prob']*10000;

				if ( $rand < $last_value)
					return $row;
			}

			return $last_row;
			
		}
	}

	function validDay($row) {
		$dayOfTheWeek = idate('w');

		switch ($dayOfTheWeek) {
		case 0:
			if ($row['sunday'] == 1)
				return true;
			break;
		case 1:
			if ($row['monday'] == 1)
				return true;
			break;
		case 2:
			if ($row['tuesday'] == 1)
				return true;
			break;
		case 3:
			if ($row['wednesday'] == 1)
				return true;
			break;
		case 4:
			if ($row['thursday'] == 1)
				return true;
			break;
		case 5:
			if ($row['friday'] == 1)
				return true;
			break;
		case 6:
			if ($row['saturday'] == 1)
				return true;
			break;
		}

		return false;
	}

	function getGlobalParameter($name) {
		global $mysqli;
		$value = $mysqli->query("SELECT value FROM global_parameters WHERE name='".$name."'");

		if ($value->num_rows > 0)
			return $value->fetch_assoc()['value'];

		return null;
	}


	post();

	echo '0';
?>
